package tr.com.netgis;

import tr.com.netgis.db.NGDbHelper;
import tr.com.netgis.db.NGDbHelper.Table;
import tr.com.netgis.log.MessagesSqlCursorAdapter;
import tr.com.netgis.pojo.Message;
import tr.com.netgis.util.LocalMessageType;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;

/**
 * 
 * @author NetGis
 *
 */
public class MessagesListActivity extends NGListActivity {

	final String SETTING_TODOLIST = "todolist";
	private ListView mainListView = null;
	private Spinner spinner;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.messages);

		spinner = (Spinner) findViewById(R.id.messagesSpinnerFilter);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.messagesFilterEntry, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View view,
					int position, long id) {
				filterMessages(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> adapterView) {}
		});
		
		
		mainListView = (ListView) findViewById(R.id.messagesList);
		mainListView.setCacheColorHint(0);
		mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		
		mainListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				//TODO option menü çıkarılabilir
				return true;
			}
			
		});
		
		mainListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showMessage(NGDbHelper.getMessage((Cursor)arg0.getItemAtPosition(arg2)));
			}
			
		});

		// Bind the data with the list
		mainListView.setItemsCanFocus(false);
		mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        new SelectDataTask().execute();		
	}
	
	private void filterMessages (int position){
		new SelectDataTask().execute(new Integer[]{position});
	}
	
	private void showMessage(Message message) {
		Intent messageActivity = new Intent(NGApplication.getAppContext(), MessageViewActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("message", message);
		messageActivity.putExtras(bundle);
		startActivity(messageActivity);		
	}
	
	@Override
    protected void onRestart() {
        new SelectDataTask().execute(new Integer[]{spinner.getSelectedItemPosition()});
        super.onRestart();
    }
	
	
	
    @Override
	protected void onResume() {
		super.onResume();
	}

	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	private class SelectDataTask extends AsyncTask<Integer, Void, String> {

		String waitMsg = getResources().getString(R.string.msgLoading);

		protected void onPreExecute() {
	        if (mCursor != null) mCursor.close();
			dialog = ProgressDialog.show(MessagesListActivity.this, "", waitMsg, true);
		}

		protected String doInBackground(final Integer... args) {
			String[] columns = NGDbHelper.getColumns(Table.MESSAGES);
			String select = "1 = 1";
			if (args != null && args.length == 1) {
				int code = args[0];
				if (code == 0) { //tüm mesajlar
				} else if (code == 1) { //metin mesajlar
					select = NGDbHelper.COL_COMMAND + " = '0'" ;
				} else if (code == 2) { //command
					select = NGDbHelper.COL_COMMAND + " > '0'" ;					
				}
			}			        
			mCursor = mDb.query(NGDbHelper.TABLE_NAME_MESSAGES, columns, select, null, null, null, null, null);									
			return null;
		}

		//can use UI thread here
		protected void onPostExecute(final String result) {
	        String[] headers = new String[] {NGDbHelper.COL_SENDER, NGDbHelper.COL_COMMAND};
	        mAdapter = new MessagesSqlCursorAdapter(MessagesListActivity.this,
	        		R.layout.messages_row,
	        		mCursor,
	        		headers, 
	                new int[]{android.R.id.text1, android.R.id.text2},
	        		mHelper);
	        mainListView.setAdapter(mAdapter);
	        dismissProgress();
		}
	}
	
	ProgressDialog dialog;

	private void dismissProgress() {
		dialog.dismiss();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = this.getMenuInflater();
	    inflater.inflate(R.menu.menu_refresh_delete_new, menu);
		super.onCreateOptionsMenu(menu);
	    return true;
	}
	
	private void trash(){
		Intent intent = new Intent(this, MessagesDeleteListActivity.class);
        startActivity(intent);	
	}
	
	private void refresh(){
        new SelectDataTask().execute(new Integer[]{spinner.getSelectedItemPosition()});		
	}

	private void newMessage(LocalMessageType type){
		Intent act = new Intent(MessagesListActivity.this, LocalMessageViewActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("type", type);
		act.putExtras(bundle);
		startActivity(act);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.menu_refresh:
	        refresh();
	        return true;
	    case R.id.menu_trash:
	        trash();
	        return true;
	    case R.id.menu_newMessage:
	        return true;
	    case R.id.createMessageTypeText:
	    	newMessage(LocalMessageType.TEXT);
	        return true;
	    case R.id.createMessageTypeAlarm:
	    	newMessage(LocalMessageType.ALARM);
	        return true;
	   
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	
	
}
